package com.example.expandablelistdemo;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;

public class MainActivity extends Activity {

	private Activity activity;
	private ExpandableListView listView;
	private ListAdapter adapter;
	private List<ForumData> listData;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_main);
		activity = this;
		listData = Util.getData();
		
		initView();
	}

	private void initView() {
		listView = (ExpandableListView) findViewById(R.id.ex_forumlist);
		
		adapter = new ListAdapter(activity, listData);
		listView.setAdapter(adapter);
		
		listView.setSelectedGroup(0);
		listView.setOnChildClickListener(new OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				
				if(listData ==null || listData.size() <=0){
					return false;
				}
				
				if(listData.get(groupPosition).getDataList() !=null && listData.get(groupPosition).getDataList().size() > 0){
					String childid = listData.get(groupPosition).getDataList().get(childPosition).getId();
					String childname = listData.get(groupPosition).getDataList().get(childPosition).getName();
					Toast.makeText(activity, childid+" --> "+childname, Toast.LENGTH_SHORT).show();
					return true;
				}
				
				return false;
			}
		});
		
		listView.setOnGroupExpandListener(new OnGroupExpandListener() {
			
			@Override
			public void onGroupExpand(int groupPosition) {
				if(listData ==null || listData.size() <=0){
					return;
				}
				
				List<ForumData> item = listData.get(groupPosition).getDataList();
				if(item == null){
					return;
				}
				
				for(int i=0; i<item.size() ;i++){
					if(groupPosition !=i){
						listView.collapseGroup(i);
					}
				}
				
				listView.setSelectedGroup(groupPosition);
			}
		});
		
		listView.setOnGroupClickListener(new OnGroupClickListener() {
			
			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				
				
				return false;
			}
		});
	}

}
